package cn.laixueit.service.impl;

import cn.laixueit.mapper.StudentMapper;
import cn.laixueit.pojo.Student;
import cn.laixueit.pojo.StudentExample;
import cn.laixueit.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;


    @Override
    public PageInfo<Student> list(Integer startpage,Integer pagesize,String name,Integer cid) {

        Student student = new Student();
        student.setName(name);
        student.setCid(cid);
        StudentExample example = getStudentExample(student);


        PageHelper.startPage(startpage,pagesize);
        List<Student> studentList = studentMapper.selectByExample(example);
        PageInfo<Student> pageInfo = new PageInfo<>(studentList);
        return pageInfo;
    }

    @Override
    public void save(Student student) {
        try {
            Date birthday = student.getBirthday();
            int birthdayYear = birthday.getYear()+1900;

            student.setAge(LocalDate.now().getYear()-birthdayYear);

            studentMapper.insertSelective(student);
        }catch (Exception e){
            throw new RuntimeException("学生保存发生异常");
        }
    }


    @Override
    public void del(Integer id) {
        try {
            studentMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            throw  new RuntimeException("删除异常");
        }
    }

    @Override
    public Student findStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Student student) {

        Integer jsoStudentId = student.getId();
        Student dbStudent = studentMapper.selectByPrimaryKey(jsoStudentId);

        int month = dbStudent.getBirthday().getMonth();
        int day = dbStudent.getBirthday().getDate();

        Integer age = student.getAge();
        Integer byear = LocalDate.now().getYear() - age;

        Date birthday = new Date(byear-1900, month, day);
        student.setBirthday(birthday);
        studentMapper.updateByPrimaryKeySelective(student);
    }

    private StudentExample getStudentExample(Student student){
        StudentExample example = new StudentExample();
        StudentExample.Criteria criteria = example.createCriteria();

        if(student!=null){
            if(student.getName()!=null && !"".equals(student.getName().trim())){
                criteria.andNameLike("%"+student.getName()+"%");
            }
            if(student.getCid()!=null && student.getCid()!=0){
                criteria.andCidEqualTo(student.getCid());
            }
        }

        return example;
    }
}
